<?php

namespace app\index\controller;

use think\Controller;


class Common extends Controller
{
    private $resultData = array();

    //http错误返回码
    static $_status = array(
        // Informational 1xx
        100 => "Continue",
        101 => "Switching Protocols",
        // Success 2xx
        200 => "OK",
        201 => "Created",
        202 => "Accepted",
        203 => "Non-Authoritative Information",
        204 => "No Content",
        205 => "Reset Content",
        206 => "Partial Content",
        // Redirection 3xx
        300 => "Multiple Choices",
        301 => "Moved Permanently",
        302 => "Moved Temporarily ", // 1.1
        303 => "See Other",
        304 => "Not Modified",
        305 => "Use Proxy",
        // 306 is deprecated but reserved
        307 => "Temporary Redirect",
        // Client Error 4xx
        400 => "Bad Request",
        401 => "Unauthorized",
        402 => "Payment Required",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        406 => "Not Acceptable",
        407 => "Proxy Authentication Required",
        408 => "Request Timeout",
        409 => "Conflict",
        410 => "Gone",
        411 => "Length Required",
        412 => "Precondition Failed",
        413 => "Request Entity Too Large",
        414 => "Request-URI Too Long",
        415 => "Unsupported Media Type",
        416 => "Requested Range Not Satisfiable",
        417 => "Expectation Failed",
        // Server Error 5xx
        500 => "Internal Server Error",
        501 => "Not Implemented",
        502 => "Bad Gateway",
        503 => "Service Unavailable",
        504 => "Gateway Timeout",
        505 => "HTTP Version Not Supported",
        509 => "Bandwidth Limit Exceeded",
    );

    public $uid = "";

    public $token = 0;

    public $time = 0;

    public function initialize()
    {
        header("content-type:application:json;charset=utf8");
        header("Access-Control-Allow-Credentials:true");
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:*");
        header("Access-Control-Allow-Headers:*");
       // $header = (new \think\Request)->header();

        $this->time = time();
        if (isset($_SERVER["HTTP_TIME"])) {
            $this->time = $_SERVER["HTTP_TIME"];
        }
        if (isset($_SERVER["HTTP_TOKEN"])) {
            $this->token = $_SERVER["HTTP_TOKEN"];
        }
        if (isset($_SERVER["HTTP_UID"])) {
            $this->uid = $_SERVER["HTTP_UID"];
        }
    }


    /**
     * 验证用户是否登录
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isCheckAuth()
    {
        if ($this->token && $this->uid && $this->time) {
            $this->check_action_token($this->time, $this->token, $this->uid);
        } else {
            $this->rest(['token,uid,time为空'], "s003");
        }
        return $this->uid;
    }

    /**
     * 检查token，必须登录
     * @param $time
     * @param $check_token
     * @param $user_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check_action_token($time, $check_token, $user_id)
    {
        if ($user_id > 0) {
            $user_token = db("user_token")->where(["uid" => $user_id])->find();
//            $token = md5($user_token["token"] . $user_id . $time);
            $token = $user_token["token"];
            if ($token != $check_token) {
                $this->rest([], "s003");
            }
        } else {
            $this->rest([], "s003");
        }
    }


    /**
     * 更加header获取用户信息不验证登录
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserInfo()
    {
        if ($this->token && $this->uid && $this->time) {
            if ($this->get_action_token($this->time, $this->token, $this->uid)) {
                return db("user")->find($this->uid);
            }
        }
        return null;
    }

    /**
     * 验证token是否正确，不强制登录
     * @param $time
     * @param $check_token
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_action_token($time, $check_token, $user_id)
    {
        if ($user_id > 0) {
            $user_token = db("user_token")->where(["uid" => $user_id])->find();
//            $token = md5($time . $user_token["token"] . $user_id);
            $token = $user_token["token"];
            if ($token != $check_token) {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * rest数据返回
     *
     * @param object $data 返回的数据
     * @param string $errorCode 自定义错误码
     * @param int $httpCode 定义的http错误码
     */
    protected function rest($data = null, $errorCode = "0000", $httpCode = null)
    {
        $this->resultData["data"] = $data;
        $code = $this->returnMessage($errorCode, $httpCode);

        if ($errorCode == "s004") {
            $this->resultData["message"] = $this->resultData["data"];
            $this->resultData["data"] = "";
        }
        $this->returnClient($this->resultData, $code);
    }

    /**
     * 组织返回的提示信息
     *
     * @param string $errorCode 错误提示码
     * @param int $httpCode http错误码
     * @return int|string 返回错误码
     */
    private function returnMessage($errorCode, $httpCode)
    {
        //errorCode 等于0000
        switch ($errorCode) {
            case "0000":
                $code = "200";
                break;
            case "s001":
            case "s002":
                $code = "500";
                break;
            case "s003":
                $code = "200";
                break;
            case "s004":
                $code = "200";
                break;
            case "s005":
                $code = "404";
                break;
            default:
                $code = ($httpCode == "") ? 404 : $httpCode;
                break;
        }
        $this->resultData["code"] = $errorCode;
        $message = config("error.Msg")[$errorCode];
        if ($message == null || $message == "") {
            $code = 500;
            $this->resultData["data"] = "";
            $this->resultData["message"] = "没有定义{$errorCode}的返回信息，请提示服务端工程师修改";
        } else {
            $this->resultData["code"] = $errorCode;
            $this->resultData["message"] = $message;
        }

        //返回错误
        return $code;
    }

    /**
     * 将组织好的数据返回给客户端
     *
     * @param $data
     * @param $code
     */
    private function returnClient($data, $code)
    {
        header("HTTP/1.1 " . $code . " " . self::$_status[$code]);
        header("Content-Type: application/json;charset=utf-8");

        $jsonStr = json_encode($data, JSON_UNESCAPED_UNICODE);
        exit($jsonStr);
    }

    /**
     * 请求错误方法返回
     */
    protected function _empty()
    {
        $this->rest("", "s002", 404);
    }

}
